package rssgate;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rssgate.dao.PMF;
import rssgate.dao.entity.Feed;
import rssgate.util.LogUtils;

import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class ManageRssServiceServlet extends HttpServlet implements ManageCommandConstants{
	private static final Logger log = Logger.getLogger(InstallServiceServlet.class
			.getName());
	private PrintWriter writer;
	
	public void service(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		writer = resp.getWriter();
		String msg = "INFO: Manage RSS";		
		LogUtils.logMsg(log, msg,writer);
		
		final String command = req.getParameter(COMMAND);
		
		if(ADD_COMMAND.equalsIgnoreCase(command))
		{
			final String url = req.getParameter(VALUE_URL);
			if(url!=null && url.length()!=0)
			{
				addRSS(url);
			}
		}
		if(REMOVE_COMMAND.equalsIgnoreCase(command))
		{
			final String strId = req.getParameter(VALUE_ID);
			Long id = null;
			try {
				id = Long.decode(strId);
			} catch (Exception e) {
				LogUtils.logError(log, "ERROR: Given id is not Long: " + e.getMessage(), writer);
			}
			removeRss(id);
		}		
		
		resp.sendRedirect("/rsslist.jsp");
	}	
	
	private void removeRss(Long id)
	{
		final PersistenceManager persistenceManager = getPersistenceManager();
		String query = "select from " + Feed.class.getName() + " where id==" + id;
		final List<Feed> list = (List<Feed>)persistenceManager.newQuery(query).execute();
		if(!list.isEmpty())
		{
			final Feed feed = list.get(0);
			persistenceManager.deletePersistent(feed);
		}
		persistenceManager.close();
		// all other items will be removed after
	}
	
	private void addRSS(String url)
	{
		try {
			final URL uri = new URL(url);
		} catch (MalformedURLException e) {
			LogUtils.logError(log, "ERROR: " + e.getMessage(), writer);
			return;
		}
		final PersistenceManager persistenceManager = getPersistenceManager();
		final Feed feed = new Feed();
		feed.setUrl(url);
		feed.setTitle(new Text(url));
		feed.setSubtitle(new Text(url));
		feed.setLastUpdate(new Date(0));
		persistenceManager.makePersistent(feed);
		persistenceManager.close();		
	}
	
	private PersistenceManager getPersistenceManager() {		
		return PMF.get().getPersistenceManager();		
	}
}
